import { unitMap } from '@/config';
import { formatUnit } from './format';
import { precisionNumber } from '@/utils';

type fieldDefinitionsType = {
  label: string;
  key: string;
  path: string;
  format?: (value: number | string, array?: { path: string; value: string | number }[]) => string | number;
  precision?: number;
  unit?: string;
};

const ctrlModeType = {
  '0x00': '手控',
  '0x01': '程控',
};

const IsSelectType = {
  '0x00': '否',
  '0x01': '是',
};

const tripFlagType = {
  '0x00': '未动作',
  '0x01': '动作',
  '0x02': '返回',
};

const groupType = {
  '0x00': '相电压',
  '0x01': '线电压',
  '0x02': '序电压',
  '0x03': '相电流',
  '0x04': '线电流',
  '0x05': '序电流',
  '0x06': '短路阻抗',
  '0x07': '任意方式',
  '0x08': '功率',
  '0x09': '系统频率',
  '0x10': '直流电压Ud',
  '0x11': '直流电流Id',
  '0x12': '和电流',
};

const type = {
  '0x01': '电压电流',
  '0x02': '状态序列',
};

const returnModeType = {
  '0x00': '动作返回',
  '0x01': '全程变化',
};

const modeType = {
  '0x00': '始-终',
  '0x01': '始-终-始',
};

const IsDCType = {
  '0x00': '交流',
  '0x01': '直流',
};

const boutStateType = {
  '0x00': '断开',
  '0x01': '闭合',
};

const endModeType = {
  '0x00': '按键触发',
  '0x01': '时间触发',
  '0x03': '开入接点触发',
};

const binAndOrType = {
  '0x00': '逻辑与',
  '0x01': '逻辑或',
};

const binSelectType = {
  '0x00': '不选',
  '0x01': '选中',
};

const isFaultIdType = {
  '0x00': '不叠加',
  '0x01': '叠加',
};

const faultIdModeType = {
  '0x00': '自动计算',
  '0x01': '手动设置',
};

const binTripRefType = {
  '0x00': '第一状态',
  '0x01': '上一状态',
};

const phaseModeType = {
  '0x00': '状态关联',
  '0x01': '状态独立',
};

const eleFieldDefinitions: fieldDefinitionsType[] = [
  {
    key: 'type',
    label: '类型',
    path: 'type',
    format: value => formatUnit(value, type),
  },
  {
    key: 'CtrlMode',
    label: '试验控制方式',
    path: 'params.CtrlMode',
    format: value => formatUnit(value, ctrlModeType),
  },
  {
    key: 'RepeatNumbers',
    label: '重复次数',
    path: 'params.RepeatNumbers',
  },
  {
    key: 'Group',
    label: '变量组别',
    path: 'params.Group',
    format: value => formatUnit(value, groupType),
  },
  {
    key: 'prop',
    label: '变量类型',
    path: 'params.prop',
    format: (value, arr) => formatProp(Number(value), arr),
  },
  {
    key: 'VarID',
    label: '变量ID',
    path: 'params.VarID',
  },
  {
    key: 'id',
    label: '变量ID',
    path: 'params.id',
  },
  {
    key: 'VaryMode',
    label: '变化方式',
    path: 'params.VaryMode',
    format: value => formatUnit(value, modeType),
  },
  {
    key: 'VaryFrom',
    label: '变化起点',
    path: 'params.VaryFrom',
    precision: 2,
  },
  {
    key: 'VaryTo',
    label: '变化终点',
    path: 'params.VaryTo',
    precision: 2,
  },
  {
    key: 'Step',
    label: '变化步长',
    path: 'params.Step',
    precision: 2,
  },
  {
    key: 'StepTime',
    label: '变化每步时间',
    path: 'params.StepTime',
    unit: unitMap['0x28'],
  },
  {
    key: 'ReturnMode',
    label: '返回方式',
    path: 'params.ReturnMode',
    format: value => formatUnit(value, returnModeType),
  },
  {
    key: 'IsSelect',
    label: '参与平均值计算',
    path: 'result.arrayRslt[*].IsSelect',
    format: value => formatUnit(value, IsSelectType),
  },
  {
    key: 'TripFlag',
    label: '跳闸标志',
    path: 'result.arrayRslt[*].TripFlag',
    format: value => formatUnit(value, tripFlagType),
  },
  {
    key: 'TripTime',
    label: '跳闸时间',
    path: 'result.arrayRslt[*].TripTime',
    precision: 2,
    unit: unitMap['0x28'],
  },
  {
    key: 'TripValue',
    label: '动作值',
    path: 'result.arrayRslt[*].TripValue',
    precision: 2,
  },
  {
    key: 'VarGroup',
    label: '记录变量组别',
    path: 'result.arrayRslt[*].VarGroup',
    format: value => formatUnit(value, groupType),
  },
  {
    key: 'VarProp',
    label: '记录变量类型',
    path: 'result.arrayRslt[*].VarProp',
    format: (value, arr) => formatProp(Number(value), arr),
  },
];

const stateFieldDefinitions: fieldDefinitionsType[] = [
  {
    key: 'type',
    label: '类型',
    path: 'type',
    format: value => formatUnit(value, type),
  },
  {
    key: 'Ua.Mag',
    label: 'Ua幅值',
    path: 'params.States[*].Ua.Mag',
    unit: unitMap['0x05'],
    precision: 2,
  },
  {
    key: 'Ua.Ang',
    label: 'Ua角度',
    path: 'params.States[*].Ua.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Ua.Fre',
    label: 'Ua频率',
    path: 'params.States[*].Ua.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Ua.IsDC',
    label: 'Ua是否直流',
    path: 'params.States[*].Ua.IsDC',
    format: value => formatUnit(value, IsDCType),
  },
  {
    key: 'Ub.Mag',
    label: 'Ub幅值',
    path: 'params.States[*].Ub.Mag',
    unit: unitMap['0x05'],
    precision: 2,
  },
  {
    key: 'Ub.Ang',
    label: 'Ub角度',
    path: 'params.States[*].Ub.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Ub.Fre',
    label: 'Ub频率',
    path: 'params.States[*].Ub.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Ub.IsDC',
    label: 'Ub是否直流',
    path: 'params.States[*].Ub.IsDC',
    format: value => formatUnit(value, IsDCType),
  },

  {
    key: 'Uc.Mag',
    label: 'Uc幅值',
    path: 'params.States[*].Uc.Mag',
    unit: unitMap['0x05'],
    precision: 2,
  },
  {
    key: 'Uc.Ang',
    label: 'Uc角度',
    path: 'params.States[*].Uc.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Uc.Fre',
    label: 'Uc频率',
    path: 'params.States[*].Uc.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Uc.IsDC',
    label: 'Uc是否直流',
    path: 'params.States[*].Uc.IsDC',
    format: value => formatUnit(value, IsDCType),
  },
  {
    key: 'Ux.Mag',
    label: 'Ux幅值',
    path: 'params.States[*].Ux.Mag',
    unit: unitMap['0x05'],
    precision: 2,
  },
  {
    key: 'Ux.Ang',
    label: 'Ux角度',
    path: 'params.States[*].Ux.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Ux.Fre',
    label: 'Ux频率',
    path: 'params.States[*].Ux.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Ux.IsDC',
    label: 'Ux是否直流',
    path: 'params.States[*].Ux.IsDC',
    format: value => formatUnit(value, IsDCType),
  },

  {
    key: 'Uy.Mag',
    label: 'Uy幅值',
    path: 'params.States[*].Uy.Mag',
    unit: unitMap['0x05'],
    precision: 2,
  },
  {
    key: 'Uy.Ang',
    label: 'Uy角度',
    path: 'params.States[*].Uy.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Uy.Fre',
    label: 'Uy频率',
    path: 'params.States[*].Uy.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Uy.IsDC',
    label: 'Uy是否直流',
    path: 'params.States[*].Uy.IsDC',
    format: value => formatUnit(value, IsDCType),
  },

  {
    key: 'Uz.Mag',
    label: 'Uz幅值',
    path: 'params.States[*].Uz.Mag',
    unit: unitMap['0x05'],
    precision: 2,
  },
  {
    key: 'Uz.Ang',
    label: 'Uz角度',
    path: 'params.States[*].Uz.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Uz.Fre',
    label: 'Uz频率',
    path: 'params.States[*].Uz.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Uz.IsDC',
    label: 'Uz是否直流',
    path: 'params.States[*].Uz.IsDC',
    format: value => formatUnit(value, IsDCType),
  },
  {
    key: 'Ia.Mag',
    label: 'Ia幅值',
    path: 'params.States[*].Ia.Mag',
    unit: unitMap['0x09'],
    precision: 2,
  },
  {
    key: 'Ia.Ang',
    label: 'Ia角度',
    path: 'params.States[*].Ia.Ang',
    unit: unitMap['0x2E'], // 角度单位（通常为°）
  },
  {
    key: 'Ia.Fre',
    label: 'Ia频率',
    path: 'params.States[*].Ia.Fre',
    unit: unitMap['0x1E'], // 频率单位（通常为Hz）
  },
  {
    key: 'Ia.IsDC',
    label: 'Ia是否直流',
    path: 'params.States[*].Ia.IsDC',
    format: value => formatUnit(value, IsDCType), // 使用相同的IsDC格式化方式
  },
  // Ib 配置
  {
    key: 'Ib.Mag',
    label: 'Ib幅值',
    path: 'params.States[*].Ib.Mag',
    unit: unitMap['0x09'], // 电流幅值单位（假设是安培 A）
    precision: 2,
  },
  {
    key: 'Ib.Ang',
    label: 'Ib角度',
    path: 'params.States[*].Ib.Ang',
    unit: unitMap['0x2E'], // 角度单位（°）
  },
  {
    key: 'Ib.Fre',
    label: 'Ib频率',
    path: 'params.States[*].Ib.Fre',
    unit: unitMap['0x1E'], // 频率单位（Hz）
  },
  {
    key: 'Ib.IsDC',
    label: 'Ib是否直流',
    path: 'params.States[*].Ib.IsDC',
    format: value => formatUnit(value, IsDCType),
  },

  // Ic 配置
  {
    key: 'Ic.Mag',
    label: 'Ic幅值',
    path: 'params.States[*].Ic.Mag',
    unit: unitMap['0x09'],
    precision: 2,
  },
  {
    key: 'Ic.Ang',
    label: 'Ic角度',
    path: 'params.States[*].Ic.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Ic.Fre',
    label: 'Ic频率',
    path: 'params.States[*].Ic.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Ic.IsDC',
    label: 'Ic是否直流',
    path: 'params.States[*].Ic.IsDC',
    format: value => formatUnit(value, IsDCType),
  },

  // Ix 配置
  {
    key: 'Ix.Mag',
    label: 'Ix幅值',
    path: 'params.States[*].Ix.Mag',
    unit: unitMap['0x09'],
    precision: 2,
  },
  {
    key: 'Ix.Ang',
    label: 'Ix角度',
    path: 'params.States[*].Ix.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Ix.Fre',
    label: 'Ix频率',
    path: 'params.States[*].Ix.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Ix.IsDC',
    label: 'Ix是否直流',
    path: 'params.States[*].Ix.IsDC',
    format: value => formatUnit(value, IsDCType),
  },

  // Iy 配置
  {
    key: 'Iy.Mag',
    label: 'Iy幅值',
    path: 'params.States[*].Iy.Mag',
    unit: unitMap['0x09'],
    precision: 2,
  },
  {
    key: 'Iy.Ang',
    label: 'Iy角度',
    path: 'params.States[*].Iy.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Iy.Fre',
    label: 'Iy频率',
    path: 'params.States[*].Iy.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Iy.IsDC',
    label: 'Iy是否直流',
    path: 'params.States[*].Iy.IsDC',
    format: value => formatUnit(value, IsDCType),
  },

  // Iz 配置
  {
    key: 'Iz.Mag',
    label: 'Iz幅值',
    path: 'params.States[*].Iz.Mag',
    unit: unitMap['0x09'],
    precision: 2,
  },
  {
    key: 'Iz.Ang',
    label: 'Iz角度',
    path: 'params.States[*].Iz.Ang',
    unit: unitMap['0x2E'],
  },
  {
    key: 'Iz.Fre',
    label: 'Iz频率',
    path: 'params.States[*].Iz.Fre',
    unit: unitMap['0x1E'],
  },
  {
    key: 'Iz.IsDC',
    label: 'Iz是否直流',
    path: 'params.States[*].Iz.IsDC',
    format: value => formatUnit(value, IsDCType),
  },
  {
    key: 'Bout1.BoutState',
    label: 'Bout1开出状态',
    path: 'params.States[*].Bout1.BoutState',
    format: value => formatUnit(value, boutStateType),
  },
  {
    key: 'Bout1.DelayTime',
    label: 'Bout1输出延时',
    path: 'params.States[*].Bout1.DelayTime',
    unit: unitMap['0x28'],
  },
  // Bout2 配置
  {
    key: 'Bout2.BoutState',
    label: 'Bout2开出状态',
    path: 'params.States[*].Bout2.BoutState',
    format: value => formatUnit(value, boutStateType),
  },
  {
    key: 'Bout2.DelayTime',
    label: 'Bout2输出延时',
    path: 'params.States[*].Bout2.DelayTime',
    unit: unitMap['0x28'],
  },

  // Bout3 配置
  {
    key: 'Bout3.BoutState',
    label: 'Bout3开出状态',
    path: 'params.States[*].Bout3.BoutState',
    format: value => formatUnit(value, boutStateType),
  },
  {
    key: 'Bout3.DelayTime',
    label: 'Bout3输出延时',
    path: 'params.States[*].Bout3.DelayTime',
    unit: unitMap['0x28'],
  },

  // Bout4 配置
  {
    key: 'Bout4.BoutState',
    label: 'Bout4开出状态',
    path: 'params.States[*].Bout4.BoutState',
    format: value => formatUnit(value, boutStateType),
  },
  {
    key: 'Bout4.DelayTime',
    label: 'Bout4输出延时',
    path: 'params.States[*].Bout4.DelayTime',
    unit: unitMap['0x28'],
  },

  // Bout5 配置
  {
    key: 'Bout5.BoutState',
    label: 'Bout5开出状态',
    path: 'params.States[*].Bout5.BoutState',
    format: value => formatUnit(value, boutStateType),
  },
  {
    key: 'Bout5.DelayTime',
    label: 'Bout5输出延时',
    path: 'params.States[*].Bout5.DelayTime',
    unit: unitMap['0x28'],
  },

  // Bout6 配置
  {
    key: 'Bout6.BoutState',
    label: 'Bout6开出状态',
    path: 'params.States[*].Bout6.BoutState',
    format: value => formatUnit(value, boutStateType),
  },
  {
    key: 'Bout6.DelayTime',
    label: 'Bout6输出延时',
    path: 'params.States[*].Bout6.DelayTime',
    unit: unitMap['0x28'],
  },

  // Bout7 配置
  {
    key: 'Bout7.BoutState',
    label: 'Bout7开出状态',
    path: 'params.States[*].Bout7.BoutState',
    format: value => formatUnit(value, boutStateType),
  },
  {
    key: 'Bout7.DelayTime',
    label: 'Bout7输出延时',
    path: 'params.States[*].Bout7.DelayTime',
    unit: unitMap['0x28'],
  },

  // Bout8 配置
  {
    key: 'Bout8.BoutState',
    label: 'Bout8开出状态',
    path: 'params.States[*].Bout8.BoutState',
    format: value => formatUnit(value, boutStateType),
  },
  {
    key: 'Bout8.DelayTime',
    label: 'Bout8输出延时',
    path: 'params.States[*].Bout8.DelayTime',
    unit: unitMap['0x28'],
  },

  // EndMode 配置
  {
    key: 'EndMode',
    label: '结束触发方式',
    path: 'params.States[*].EndMode',
    format: value => formatUnit(value, endModeType),
  },

  // 状态持续时间
  {
    key: 'MaxLastTime',
    label: '状态持续时间',
    path: 'params.States[*].MaxLastTime',
    unit: unitMap['0x28'],
  },

  {
    key: 'BinAndOr',
    label: '开入逻辑',
    path: 'params.States[*].BinAndOr',
    format: value => formatUnit(value, binAndOrType),
  },

  {
    key: 'BinSelect.A',
    label: '选择标志.A',
    path: 'params.States[*].BinSelect.A',
    format: value => formatUnit(value, binSelectType),
  },
  {
    key: 'BinSelect.B',
    label: '选择标志.B',
    path: 'params.States[*].BinSelect.B',
    format: value => formatUnit(value, binSelectType),
  },
  {
    key: 'BinSelect.C',
    label: '选择标志.C',
    path: 'params.States[*].BinSelect.C',
    format: value => formatUnit(value, binSelectType),
  },
  {
    key: 'BinSelect.R',
    label: '选择标志.R',
    path: 'params.States[*].BinSelect.R',
    format: value => formatUnit(value, binSelectType),
  },

  {
    key: 'BinSelect.a',
    label: '选择标志.a',
    path: 'params.States[*].BinSelect.a',
    format: value => formatUnit(value, binSelectType),
  },
  {
    key: 'BinSelect.b',
    label: '选择标志.b',
    path: 'params.States[*].BinSelect.b',
    format: value => formatUnit(value, binSelectType),
  },
  {
    key: 'BinSelect.c',
    label: '选择标志.c',
    path: 'params.States[*].BinSelect.c',
    format: value => formatUnit(value, binSelectType),
  },
  {
    key: 'BinSelect.r',
    label: '选择标志.r',
    path: 'params.States[*].BinSelect.r',
    format: value => formatUnit(value, binSelectType),
  },

  {
    key: 'StateName',
    label: '状态名称',
    path: 'params.States[*].StateName',
  },

  {
    key: 'm_DataRepeatNumbers',
    label: '循环输出次数',
    path: 'params.CtrlPara.m_DataRepeatNumbers',
  },

  {
    key: 'IsFaultId',
    label: '电流-是否叠加',
    path: 'params.CtrlPara.IsFaultId',
    format: value => formatUnit(value, isFaultIdType),
  },
  {
    key: 'FaultId_Mode',
    label: '电流-计算方式',
    path: 'params.CtrlPara.FaultId_Mode',
    format: value => formatUnit(value, faultIdModeType),
  },
  {
    key: 'FaultId_Id0',
    label: '电流-起始值',
    path: 'params.CtrlPara.FaultId_Id0',
    unit: unitMap['0x09'],
  },
  {
    key: 'IsFaultUd',
    label: '电压-是否叠加',
    path: 'params.CtrlPara.IsFaultUd',
    format: value => formatUnit(value, isFaultIdType),
  },
  {
    key: 'FaultUd_Mode',
    label: '电压-计算方式',
    path: 'params.CtrlPara.FaultUd_Mode',
    format: value => formatUnit(value, faultIdModeType),
  },
  {
    key: 'FaultUd_Ud0',
    label: '电压-起始值',
    path: 'params.CtrlPara.FaultUd_Ud0',
    unit: unitMap['0x09'],
  },

  {
    key: 'BinTripRef',
    label: '动作定义',
    path: 'params.CtrlPara.BinTripRef',
    format: value => formatUnit(value, binTripRefType),
  },

  {
    key: 'PhaseMode',
    label: '相位变化模式',
    path: 'params.CtrlPara.PhaseMode',
    format: value => formatUnit(value, phaseModeType),
  },
  {
    key: 'BinTripRef',
    label: '动作定义',
    path: 'result.BinTripRef',
    format: value => formatUnit(value, binTripRefType),
  },
  {
    key: 'StateEnterTime',
    label: '进入时刻',
    path: 'result.XUI_Results[*].StateEnterTime',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateDurationTime',
    label: '持续时间',
    path: 'result.XUI_Results[*].StateDurationTime',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateResultA',
    label: 'A动作时间',
    path: 'result.XUI_Results[*].A',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateResultB',
    label: 'B动作时间',
    path: 'result.XUI_Results[*].B',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateResultC',
    label: 'C动作时间',
    path: 'result.XUI_Results[*].C',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateResultR',
    label: 'R动作时间',
    path: 'result.XUI_Results[*].R',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateResulta',
    label: 'a动作时间',
    path: 'result.XUI_Results[*].a',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateResultb',
    label: 'b动作时间',
    path: 'result.XUI_Results[*].b',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateResultc',
    label: 'c动作时间',
    path: 'result.XUI_Results[*].c',
    unit: unitMap['0x28'],
    precision: 2,
  },
  {
    key: 'StateResultr',
    label: 'r动作时间',
    path: 'result.XUI_Results[*].r',
    unit: unitMap['0x28'],
    precision: 2,
  },
];

function formatProp(value: number, arr: { path: string; value: string | number }[] = []): string {
  const type = {
    0: '幅值',
    1: '角度',
  };
  const type2 = {
    0: '有功',
    1: '无功',
    2: '视在',
  };

  const group = arr.find(i => i.path === 'params.Group');
  if (!group) return value + '';
  if ([0, 1, 2, 3, 4, 5, 6].includes(group.value as number)) {
    return type[value as keyof typeof type];
  }
  if ([8].includes(group.value as number)) {
    return type2[value as keyof typeof type];
  }
  return value + '';
}

/**
 * 递归地将一个包含嵌套属性的对象扁平化为一个包含路径和值属性的对象数组。
 */
function flattenObjectWithPath(obj: { [key: string]: unknown }, parentPath = ''): { path: string; value: string | number }[] {
  const result: { path: string; value: string | number }[] = [];

  for (const [key, value] of Object.entries(obj) as [string, unknown][]) {
    const currentPath = parentPath ? `${parentPath}.${key}` : key;

    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
      // 如果是对象，递归处理
      result.push(...flattenObjectWithPath(value as { [key: string]: unknown }, currentPath));
    } else if (Array.isArray(value)) {
      // 如果是数组，遍历每一项并添加索引
      (value as unknown[]).forEach((item, index) => {
        if (typeof item === 'object' && item !== null) {
          result.push(...flattenObjectWithPath(item as { [key: string]: unknown }, `${currentPath}[${index}]`));
        } else {
          result.push({ path: `${currentPath}[${index}]`, value: item as string | number });
        }
      });
    } else {
      // 基本类型（数字、字符串、布尔等）
      result.push({ path: currentPath, value: value as string | number });
    }
  }

  return result;
}

function getGroupName(group: string) {
  const groupMap = {
    params: '参数设置',
    datetime: '测试时间',
    type: '测试类型',
    result: '测试结果',
    ['result.arrayRslt']: '测试结果',
    ['params.States']: '状态列表',
    ['params.CtrlPara']: '控制参数',
    ['result.XUI_Results']: 'XUI结果',
  };
  if (groupMap[group as keyof typeof groupMap]) {
    return groupMap[group as keyof typeof groupMap];
  }
  return group;
}

function getGroup(path: string) {
  // const firstArray = ['type', 'result', 'params'];
  const secondArray = ['arrayRslt', 'XUI_Results', 'States', 'CtrlPara'];
  const res = path.replace(/\[\d+\]/, '').split('.');
  const secondArg = secondArray.includes(res[1]) ? res[1] : '';
  const group = secondArg ? `${res[0]}.${secondArg}` : res[0];
  const groupName = getGroupName(group);
  if (!secondArg) {
    return [group, groupName];
  }
  const numMatch = path.match(/\[(\d+)\]/);
  const num = numMatch ? parseInt(numMatch[1], 10) + 1 : '';
  return [group + '-' + num, groupName + num];
}

/**
 * 获取扁平化数据和字段定义，并为这些数据添加标签。
 */
function addLabelsToFlattenedData(flattenedData: { path: string; value: string | number }[], type: number) {
  const fieldDefinitions = type === 1 ? eleFieldDefinitions : stateFieldDefinitions;
  return flattenedData.map(item => {
    // 1. 检查 fieldDefinitions 中是否有匹配的 path（支持通配符 [*]）
    const matchedField = fieldDefinitions.find(field => {
      // 将定义中的 [*] 替换为正则表达式 \[\d+\]，用于匹配任意数组索引
      const regexPattern = field.path.replace(/\[\*\]/g, '\\[\\d+\\]');
      const regex = new RegExp(`^${regexPattern}$`);
      return regex.test(item.path);
    });

    // 2. 如果找到匹配项，添加 label
    if (matchedField) {
      const formatValue = matchedField.format ? matchedField.format(item.value as number, flattenedData) : item.value;
      const precisionValue = matchedField.precision ? precisionNumber(formatValue as string, matchedField.precision) : formatValue;
      const [group, groupName] = getGroup(item.path);
      return {
        ...item,
        ...matchedField,
        value: precisionValue,
        group,
        groupName: groupName,
      };
    }

    // 4. 未匹配到任何 label，返回原对象
    return {
      ...item,
      label: '',
    };
  });
}

const getCurrentDate = () => {
  const date = new Date();
  const datetime = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
  const result = { key: 'datetime', value: datetime, label: '测试时间', group: 'datetime', groupName: getGroupName('datetime') };
  return result;
};

const remark = [
  {
    label: '环境温度',
    key: 'ambientTemperature',
    value: '',
    editable: true,
    editType: 'input',
    unit: unitMap['0x11'],
    groupName: '补充信息',
  },
  {
    label: '空气湿度',
    key: 'airHumidity',
    value: '',
    editable: true,
    editType: 'input',
    unit: unitMap['0x08'],
    groupName: '补充信息',
  },
  {
    path: 'remark',
    key: 'remark',
    value: '',
    label: '备注',
    editable: true,
    editType: 'input',
    groupName: '补充信息',
  },
];

export const flattenedWithPath = (str: string) => {
  if (str === '') return [];
  const originalData = JSON.parse(str);
  const type = originalData.type;
  const res = flattenObjectWithPath(originalData);
  const resultWithLabels = addLabelsToFlattenedData(res, type);
  const dateTime = getCurrentDate();
  return [dateTime, ...remark, ...resultWithLabels];
};
